<?php

namespace App\Api\Controllers;

use App\Api\Requests\CoinRequest;
use App\Models\Coin;
use App\Models\UserLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CoinsController extends Controller
{
    public function index(Coin $coin){
        return $this->success($this->user()->coin()->orderBy('id','desc')->get());
    }

    public function store(Coin $coin,CoinRequest $request){
        // if(!$this->user()->btc_address){
        //     return $this->error('请绑定BTC地址');
        // }
        if($request->btc < 0.005){
            return $this->error('BTC0.005起提');
        }
        if($request->btc > $this->user()->btc){
            return $this->error('可提BTC不足');
        }
        if($this->user()->btc_address){
        	$btc_address = $this->user()->btc_address;
        }else{
        	$btc_address = $request->btc_address;
        }
        if(!$btc_address){
        	return $this->error('请绑定BTC地址');
        }
        $user_coin = $coin->where('user_id',$this->user()->id)->where('status',0)->get();
        if(!$user_coin->isEmpty()){
            return $this->error('还有未审核记录');
        }
        $coin->fill($request->all());
        $coin->user_id = $this->user()->id;
        $coin->btc_address = $btc_address;
        if(!$this->user()->btc_address){
        	$this->user()->update(['btc_address'=>$coin->btc_address]);
        }
        $coin->btc_img = $request->btc_img;
        if($coin->save()){
            //扣减BTC
            (new UserLog())->change(-$coin->btc,$this->user()->id,'btc',43,'会员提币');
        }
        return $this->success($coin);
    }
}
